package components.bullets.controller
{
	import actor.Demon;
	
	import capricornus.utils.PointUtils;
	
	import components.bullets.Bullet;
	import components.bullets.BulletVO;
	
	import scene.Scene;

	public class BulletMoveController
	{
		protected var _bullet:Bullet;
		
		protected var _flyLen:Number = 0;
		protected var _vo:BulletVO;
		protected var _speed:Number;
		protected var _diffHeight:int;
		protected var _endHeight:int;
		
		protected var _showLen:int = 20;//刚开始隐藏子弹，让子弹看起来像是不会是从身体里面出来的
		
		public function BulletMoveController( bullet:Bullet )
		{
			_bullet = bullet;
			init();
		}
		
		private function init():void
		{
			_vo = _bullet.vo;
			_speed = _vo.speed;
		}
		
		public function destroy():void
		{
			_bullet = null;
		}
		
		public function setInfo( endHeight:int, diffHeight:int ):void
		{
			_endHeight = endHeight;
			_diffHeight = diffHeight;
		}
		
		protected var _len:Number;
		public function refresh( time:int ):void
		{
			var arr:Array = [_bullet.x, _bullet.y];
			var arrD:Array = [_vo.demon.x, _vo.demon.y];
			_len = PointUtils.getLength( arr, arrD );
			var p:Number = _vo.speed * time;
			if( !_bullet.visible )
			{
				_flyLen += p;
				_bullet.visible = _flyLen >= _showLen;
			}
			if( p < _len )
			{
				var f:Number = 1 - p / _len;
				_bullet.container.y = -(int(_diffHeight * f) + _endHeight);
				var pt:Array = PointUtils.interpolate2( arr, arrD, _vo.speed * time, _len );
				_bullet.directFrom( arr, arrD );
				_bullet.setLocation( pt[0], pt[1] );
			}
			else
			{
				hitTarget();
				_bullet.destroy();
			}
		}
		
		protected function hitTarget():void
		{
			if( _vo.isAreaHit )
			{
				var arr:Array = Scene.instance.gridController.getDemons( _bullet.x, _bullet.y, _vo.areaHitRange );
				var len:int = arr.length;
				//这里如果要改成限制伤害个数的话，要保证_vo.demon受到伤害了
				for( var i:int=0; i<len; i++ )
				{
					(arr[i] as Demon).getHurt( _vo.damage );
				}
			}
			else
			{
				_vo.demon.getHurt( _vo.damage );
			}
			if( _vo.isStun )
			{
				_vo.demon.stun( _vo.stunDuration );
			}
		}
	}
}




















